import { Component, OnInit, OnDestroy, AfterViewInit, Renderer2, ElementRef, ViewChild } from '@angular/core';
import { FormBuilder } from '@angular/forms';

import { ConfigService } from 'src/app/config.service';
import { async } from '@angular/core/testing';
import { TimeTableOption } from 'src/app/config/shared/time-table/TimeTableInterface';
import { IeCssService } from 'src/app/shared/func-service/ie-css.service';
import { ResponseErrorService } from 'src/app/shared/func-service/response-error.service';
import { BoolEmployee, EmployeeItem } from 'src/app/shared/func-service/employee.service';
import { PublicFuncService } from 'src/app/shared/func-service/public-func.service';
import { TipsService } from 'src/app/tips/tips.service';
import { LastNavService } from 'src/app/shared/func-service/last-nav.service';
import { DiyHttpService } from 'src/app/shared/func-service/diy-http.service';
import Logger from 'src/app/logger';
import { isNumberJudge } from 'src/app/shared/validators/benumber.directive';
import { isPString32 } from 'src/app/shared/validators/pstring32.directive';


@Component({
  selector: 'app-safety-belt',
  templateUrl: './safety-belt.component.html',
  styleUrls: ['./safety-belt.component.scss']
})
export class SafetyBeltComponent implements OnInit, AfterViewInit, OnDestroy {

  @ViewChild('belt', {static: false}) configChild: any;


  constructor(
    private cfg: ConfigService,
    private fb: FormBuilder,
    private Re2: Renderer2,
    private el: ElementRef,
    private ieCss: IeCssService,
    private resError: ResponseErrorService,
    private tips: TipsService,
    private pfs: PublicFuncService,
    private lns: LastNavService,
    private dhs: DiyHttpService,
  ) { }

  private logger: Logger = new Logger('safety-belt');
  isChrome: boolean = false;
  private navGroup: string = 'belt';
  private src: string = '';
  private lastActiveTab: string = '';
  selectedTab = 'configSetting';



  
  private urlOb: any;
  

  menuItems: Array<string> = [
    'configSetting'
  ];

  tabItems: Array<string> = [
    'configSettingTab'
  ];

  
  private isSetVal: boolean = false;

Form = this.fb.group({
    id: 3,
    iEnabled: 0,
    sUrl: "",
    iFraction: 0,
    iInterval: 0
  });

  ngOnInit(): void {
    this.isChrome = this.ieCss.getChromeBool();
    this.lns.getLastNav(this.navGroup, this.el);
    this.cfg.getSafetyInterface(this.Form.get('id').value).subscribe(
      res => {
        this.resError.analyseRes(res);
        this.Form.patchValue(res);
        this.setInfoForChild();
        this.isSetVal = true;
        this.onClickTab(this.menuItems[0]);
      },
      err => {
        this.logger.error(err, 'ngOnInit:getSafetyInterface:');
        this.tips.showInitFail();
      }
    );

    this.urlOb = this.dhs.getStreamUrl().subscribe(
      (msg: string) => {
        if (msg) {
          this.src = msg;
          this.setInfoForChild();
          this.isSetVal = true;
        } else {
          this.src = null;
          this.tips.setRbTip('getVideoUrlFail');
          this.tips.showInitFail();
        }
        this.urlOb.unsubscribe();
        this.urlOb = null;
      }
    );
  }

  ngAfterViewInit() {
   
  }

  ngOnDestroy() {
    if (this.urlOb) {
      this.urlOb.unsubscribe();
    }
  }

  onSubmit() {
    
    // region submit
    this.getInfoFromChild();
    this.pfs.formatInt(this.Form.value);
    this.cfg.setSafetyInterface(this.Form.value).subscribe(
      res => {
        
        this.resError.analyseRes(res);
        this.Form.patchValue(res);
        this.setInfoForChild();
        this.tips.showSaveSuccess();
      },
      err => {
        this.logger.error(err, 'onSubmit:setSafetyInterface:');
        this.tips.showSaveFail();
      }
    );

  }

 
  onClickTab(tabName: string) {
    if (tabName !== this.lastActiveTab) {
      this.lns.setLastNav(this.navGroup, tabName + 'Tab');
      this.selectedTab = tabName;
      if (this.isSetVal) {
        this.getInfoFromChild();
      }
      switch (tabName) {
        case 'configSetting':
          this.initPlayer(tabName);
          break;
      }
      this.setChildPara(tabName);
      this.lastActiveTab = tabName;
    }
  }

  setChildPara(childName: string) {
    this.pfs.waitNavActive(5000, childName + 'Tab')
      .then(() => {
        this.setInfoForChild(childName);
      })
      .catch(() => {
        // this.tips.showInitFail();
      });
  }

  pausePlayer() {
    if (this.lastActiveTab === 'configSetting') {
      try {
        this.configChild.pausePlayer();
      } catch {}
    }
  }

  getInfoFromChild(childName: string = this.lastActiveTab) {
    
    switch (childName) {
      case 'configSetting':
        const value = this.Form.value;
        const formValue = this.configChild.getConfigInfo();
        console.log(formValue);
        value.sUrl = formValue.sUrl;
        value.iFraction = formValue.iFraction;
        value.iInterval = formValue.iInterval;
        this.Form.patchValue(value);
        break;
    }
  }

  setInfoForChild(childName: string = this.lastActiveTab) {
    switch (childName) {
      case 'configSetting':
        if (this.Form.value && this.src) {
          this.configChild.initComponent(this.Form.value, this.src);
        }
        break;
    }
  }


  async initPlayer(tabName: string) {
    this.pfs.waitNavActive(5000, tabName + 'Tab')
      .then(() => {
        // this.regionChild.resizePlayer();
        this.configChild.playEntry();
      })
      .catch(() => {
        this.tips.setRbTip('initPlayerFailFreshPlease');
      });
  }

  
}
